package cn.xiaopengstack.infrastructure.gateway.adapter;

import cn.xiaopengstack.types.enums.ResponseCode;
import cn.xiaopengstack.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author jiangyangang
 */
@Service
@Slf4j
public class GroupBuyNotifyService {

    @Resource
    private OkHttpClient okHttpClient;

    /**
     * 拼团回调
     * @param url
     * @param bodyJson
     * @return
     */
    public String groupBuyNotify(String url, String bodyJson){
        try {
            // 构建参数
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody requestBody = RequestBody.create(mediaType, bodyJson);
            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .addHeader("content-type", "application/json")
                    .build();

            Response response = okHttpClient.newCall(request).execute();

            return response.body().string();
        } catch (Exception e) {
            log.error("拼团回调失败 HTTP 接口异常 {}", url, e);
            throw new AppException(ResponseCode.HTTP_EXCEPTION);
        }
    }
}
